package com.jonah.config;

import com.jonah.pojo.Configuration;
import com.jonah.pojo.MappedStatement;
import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Jonah.Chen
 * @Date: 2020/8/5 22:24
 * @Description:
 */
@Data
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> selectElements = rootElement.selectNodes("//select");
        List<Element> insertElements = rootElement.selectNodes("//insert");
        List<Element> updateElements = rootElement.selectNodes("//update");
        List<Element> deleteElements = rootElement.selectNodes("//delete");
        List<Element> elements = new ArrayList<>();
        elements.addAll(selectElements);
        elements.addAll(insertElements);
        elements.addAll(updateElements);
        elements.addAll(deleteElements);
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramType = element.attributeValue("paramType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement(id, resultType, paramType, sql);
            configuration.getMappedStatementMap().put(namespace.concat(".").concat(id), mappedStatement);
        }
    }
}